package com.wufun.overseas.main.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.databind.JavaType;
import com.wufun.baselibrary.net.HttpUtils;
import com.wufun.overseas.R;
import com.wufun.overseas.adapters.SearchDetailAdapter;
import com.wufun.overseas.main.base.MyActivity;
import com.wufun.overseas.main.base.MyApplication;
import com.wufun.overseas.models.bean.MySearchDetailBean;
import com.wufun.overseas.rpc.RpcConstant;
import com.wufun.overseas.utils.JsonMapper;
import com.wufun.overseas.view.IXListViewLoadMore;
import com.wufun.overseas.view.IXListViewRefreshListener;
import com.wufun.overseas.view.XListView2;
import com.wufun.overseas.view.ptr.PtrClassicFrameLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SearchDetailActcivity extends MyActivity implements View.OnClickListener {

    @Bind(R.id.bar_back_iv)
    ImageView iv_back;
    @Bind(R.id.edit_search_detail)
    EditText edit_serrch;
    @Bind(R.id.iv_search_detail)
    ImageView iv_search;
    @Bind(R.id.list_search_detail)
    XListView2 listview;
    @Bind(R.id.bar_back_ll)
    LinearLayout layout_back;
    @Bind(R.id.mPtrFrame_search)
    PtrClassicFrameLayout swipeRefreshView;
    private int page = 1;
    List<MySearchDetailBean.DataBean.ResBean> datas = new ArrayList<>();
    SearchDetailAdapter adapter;
    private String keyword = "";
    private boolean isLoading = false;
    private int PreIndex = 0;
    private String fid;
    private int Jumptype = 0;
    private boolean isFirstpage = false;
    private  boolean isEn=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_detail_actcivity);
        ButterKnife.bind(this);
        initM();
        Intent intent = getIntent();
        rootBarRl.setVisibility(View.GONE);     //隐藏继承的标题
        fid = intent.getStringExtra("FID");
        if (fid == null || fid.isEmpty())
            Jumptype = 2;
        else
            Jumptype = 1;

        listview.setPullRefreshEnable(new IXListViewRefreshListener() {
            @Override
            public void onRefresh() {
                if (isLoading)
                    return;
                page = 1;
                PreIndex = 0;
                isFirstpage = true;
                getNetData();
            }
        });
        listview.setPreLoadCount(6);
        listview.setPullLoadEnable(new IXListViewLoadMore() {
            @Override
            public void onLoadMore() {
                if (isLoading)
                    return;
                getNetData();
            }
        });
    }

    private void initM() {

        layout_back.setOnClickListener(this);
//        edit_serrch.setOnClickListener(this);
        iv_search.setOnClickListener(this);

        edit_serrch.setOnEditorActionListener(EnterListenter);

        //ListView item 的点击事件  跳转的事帖子详情。type 为1
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(SearchDetailActcivity.this, PostDetailsActivtiy.class);
                intent.putExtra("Tid", datas.get(position).getPid());   //帖子id
                intent.putExtra("type", 2);                                          //type
                intent.putExtra("title", datas.get(position).getSubject());
                startActivity(intent);

            }
        });
    }

    private TextView.OnEditorActionListener EnterListenter = new TextView.OnEditorActionListener() {
        /**
         * 参数说明
         * @param v 被监听的对象
         * @param actionId  动作标识符,如果值等于EditorInfo.IME_NULL，则回车键被按下。
         * @param event    如果由输入键触发，这是事件；否则，这是空的(比如非输入键触发是空的)。
         * @return 返回你的动作
         */
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                isEn=false;
                page = 1;
                keyword = "";
                keyword = edit_serrch.getText().toString().trim();
                if (keyword.equals("")) {
                    showToast(getResources().getString(R.string.toast_search_empty_str));
                } else if (!keyword.equals("")) {
                    getNetData();
                }

            }
            return false;
        }
    };

    public void getNetData() {
//        String keyword = edit_serrch.getText().toString();
        if (page == 1) {
            datas.clear();
        }

        isLoading = true;
        if (Jumptype == 1) {
            HttpUtils.doGet(RpcConstant.forumRootUrl + "/forum/search/index?keyword=" + keyword + "&page=" + (page++) + "&limit=10&fid=" + fid, new Callback() {
                MySearchDetailBean md;

                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        JavaType javaType = JsonMapper.getInstance().createCollectionType(MySearchDetailBean.class);
                        md = JsonMapper.getInstance().fromJson(response.body().string(), javaType);
                        if (md != null && md.getData().getRes().size() > 0) {
                            if (md.getData().getRes().size() < 10) {
                                Message msg = new Message();
                                msg.what = 2;
                                cwjHandler.sendMessage(msg);
                            }
                            if (isFirstpage) {
                                datas.clear();
                                isFirstpage = false;
                            }
                            datas.addAll(md.getData().getRes());
                            Message msg = new Message();
                            msg.what = 1;
                            cwjHandler.sendMessage(msg);
                        } else {
                            Message msg = new Message();
                            msg.what = 4;
                            cwjHandler.sendMessage(msg);
                        }

                    } catch (IOException e) {
                        Message msg = new Message();
                        msg.what = 3;
                        cwjHandler.sendMessage(msg);
                        e.printStackTrace();
                    }
                }
            });
        } else if (Jumptype == 2) {
            HttpUtils.doGet(RpcConstant.forumRootUrl + "/forum/search/index?keyword=" + keyword + "&page=" + (page++) + "&limit=10", new Callback() {
                MySearchDetailBean md;

                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        JavaType javaType = JsonMapper.getInstance().createCollectionType(MySearchDetailBean.class);
                        md = JsonMapper.getInstance().fromJson(response.body().string(), javaType);
                        if (md != null && md.getData().getRes() != null && md.getData().getRes().size() > 0) {
                            if (md.getData().getRes().size() < 10) {
                                Message msg = new Message();
                                msg.what = 2;
                                cwjHandler.sendMessage(msg);
                            }
                            if (isFirstpage) {
                                datas.clear();
                                isFirstpage = false;
                            }
                            datas.addAll(md.getData().getRes());
                            Message msg = new Message();
                            msg.what = 1;
                            cwjHandler.sendMessage(msg);
                        } else {
                            Message msg = new Message();
                            msg.what = 4;
                            cwjHandler.sendMessage(msg);
                        }
                    } catch (IOException e) {
                        Message msg = new Message();
                        msg.what = 3;
                        cwjHandler.sendMessage(msg);
                        e.printStackTrace();
                    }
                }
            });
        } else {
            Toast.makeText(SearchDetailActcivity.this, "", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_search_detail:
                isEn=false;
                page = 1;
                keyword = "";
                keyword = edit_serrch.getText().toString().trim();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(edit_serrch.getWindowToken(), 0);
                if (keyword.equals("")) {
                    Toast.makeText(SearchDetailActcivity.this, "Can't be empty", Toast.LENGTH_SHORT).show();
                    return;

                }
                getNetData();

//                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                break;
            case R.id.bar_back_ll:
                finish();
                break;

        }
    }

    @SuppressLint("HandlerLeak")
    Handler cwjHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1://成功 高速UI线程可以更新结果了

                    updateUI();
                    break;
                case 2://没有返回数据
                    listview.setNoMore();
                    if (adapter != null)
                        adapter.notifyDataSetChanged();
                    break;
                case 3:
                    Toast.makeText(SearchDetailActcivity.this, getString(R.string.getnetdata_error), Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    if (isEn==false){
                        Toast.makeText(SearchDetailActcivity.this, getString(R.string.getnetdata_nomore), Toast.LENGTH_SHORT).show();
                    }
                    listview.setNoMore();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(edit_serrch.getWindowToken(), 0);
                    if (adapter != null)
                        adapter.notifyDataSetChanged();
                    break;
            }
            stopLoad();
        }
    };

    private void stopLoad() {
        listview.stopLoadMore();
        listview.stopRefresh();
        isLoading = false;
    }


    private void updateUI() {
        if (adapter == null) {
            adapter = new SearchDetailAdapter(SearchDetailActcivity.this, datas);
            listview.setAdapter(adapter);
        }
        adapter.notifyDataSetChanged();
        if (PreIndex == datas.size() && datas.size() != 0) {
            listview.setNoMore();
            return;
        }
        PreIndex = datas.size();
    }


}
